package com.tencent.sr.iris.basic.saas.dependency.user;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.tencent.sr.iris.basic.saas.common.utils.HttpUtils;
import com.tencent.sr.iris.user.core.service.interfaces.client.level.LevelClient;
import com.tencent.sr.iris.user.core.service.interfaces.client.relation.SupervisorRelationClient;
import com.tencent.sr.iris.user.core.service.interfaces.client.staff.IrisStaffClient;
import com.tencent.sr.iris.user.core.service.interfaces.client.user.UserWideCoreClient;
import com.tencent.sr.iris.user.core.service.interfaces.dto.user.UserWideDTO;
import com.tencent.sr.iris.user.core.service.interfaces.request.level.UserLevelBatchRequest;
import com.tencent.sr.iris.user.core.service.interfaces.request.relation.BatchSupervisorRequest;
import com.tencent.sr.iris.user.core.service.interfaces.request.staff.StaffDataPermDqGroupIdRequest;
import com.tencent.sr.iris.user.core.service.interfaces.request.user.IrisUserWideListQueryRequest;
import com.tencent.sr.iris.user.core.service.interfaces.response.level.UserLevelBatchResponse;
import com.tencent.sr.iris.user.core.service.interfaces.response.level.UserLevelResponse;
import com.tencent.sr.iris.user.core.service.interfaces.response.relation.SupervisorUserResponse;
import com.tencent.sr.iris.user.core.service.interfaces.response.staff.StaffDataPermDqGroupIdResponse;
import com.tencent.sr.iris.user.core.service.interfaces.response.user.UserWideListResponse;
import com.tencent.sr.rmall.common.exception.TMallBizException;
import com.tencent.sr.rmall.common.primitive.HttpResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component
public class UserDependency {

    @Value("${iris.user.max.batch.size:100}")
    private int maxSize;

    @Resource
    private LevelClient levelClient;

    @Resource
    private UserWideCoreClient userWideCoreClient;

    @Resource
    private SupervisorRelationClient supervisorRelationClient;

    @Resource
    private IrisStaffClient irisStaffClient;

    public StaffDataPermDqGroupIdResponse queryStaffDqGroupIdListByUid(String uid) {
        StaffDataPermDqGroupIdRequest request = new StaffDataPermDqGroupIdRequest();
        request.setUid(uid);
        log.info("调用UserDependency.queryBatchSupervisor，请求参数：{}", JSON.toJSONString(request));
        HttpResult<StaffDataPermDqGroupIdResponse> result = irisStaffClient.queryStaffDqGroupIdListByUid(request);
        log.info("调用UserDependency.queryBatchSupervisor，请求参数：{}，请求结果：{}",
                JSON.toJSONString(request), JSON.toJSONString(result));

        StaffDataPermDqGroupIdResponse dqGroupIdResponse = HttpUtils.handleResult(result);
        if (dqGroupIdResponse == null) {
            throw new TMallBizException("获取员工数据权限失败");
        }
        return dqGroupIdResponse;
    }

    /**
     * 获取用户等级信息
     *
     * @param uidList
     * @return
     */
    public Map<String, SupervisorUserResponse> getSupervisorMap(List<String> uidList) {
        BatchSupervisorRequest request = new BatchSupervisorRequest();
        request.setUidList(uidList);
        List<SupervisorUserResponse> responses = queryBatchSupervisor(request);

        return responses.stream().collect(Collectors.toMap(
                SupervisorUserResponse::getUid, i -> i, (i1, i2) -> i1));
    }

    /**
     * 获取用户等级信息
     *
     * @param uidList
     * @return
     */
    public Map<String, UserLevelResponse> getUserLevelMap(Long saasId, List<String> uidList) {
        UserLevelBatchRequest levelBatchRequest = new UserLevelBatchRequest();
        levelBatchRequest.setUidList(uidList);
        levelBatchRequest.setSaasId(String.valueOf(saasId));
        List<UserLevelResponse> responses = queryBatchUserLevel(levelBatchRequest);

        return responses.stream().collect(Collectors.toMap(
                UserLevelResponse::getUid, i -> i, (i1, i2) -> i1));
    }

    /**
     * 获取用户信息
     *
     * @param uidList
     * @return
     */
    public Map<String, UserWideDTO> getUserInfoMap(Long saasId, List<String> uidList) {
        IrisUserWideListQueryRequest batchQueryRequest = new IrisUserWideListQueryRequest();
        batchQueryRequest.setSaasId(saasId);
        batchQueryRequest.setUidList(uidList);

        List<UserWideDTO> users = batchQueryUserInfo(batchQueryRequest);
        return users.stream().filter(i -> StrUtil.isNotBlank(i.getUid())).collect(Collectors.toMap(
                UserWideDTO::getUid, i -> i, (i1, i2) -> i1));
    }

    /**
     * 批量查询用户导师
     *
     * @param request
     * @return
     */
    public List<SupervisorUserResponse> queryBatchSupervisor(BatchSupervisorRequest request) {

        log.info("调用UserDependency.queryBatchSupervisor，请求参数：{}", JSON.toJSONString(request));
        List<String> uidList = request.getUidList();
        ArrayList<SupervisorUserResponse> resList = Lists.newArrayListWithCapacity(uidList.size());
        List<List<String>> partition = Lists.partition(uidList, maxSize);
        for (List<String> list : partition) {
            request.setUidList(list);
            resList.addAll(doQueryBatchSupervisor(request));
        }

        log.info("调用UserDependency.queryBatchSupervisor，请求参数：{}，请求结果：{}",
                JSON.toJSONString(request), JSON.toJSONString(resList));
        return resList;
    }

    /**
     * 批量查询用户等级
     *
     * @param request
     * @return
     */
    public List<UserLevelResponse> queryBatchUserLevel(UserLevelBatchRequest request) {

        log.info("调用UserDependency.queryBatchUserLevel，请求参数：{}", JSON.toJSONString(request));
        List<String> uidList = request.getUidList();
        ArrayList<UserLevelResponse> resList = Lists.newArrayListWithCapacity(uidList.size());
        List<List<String>> partition = Lists.partition(uidList, maxSize);
        for (List<String> list : partition) {
            request.setUidList(list);
            resList.addAll(doQueryBatchUserLevel(request));
        }

        log.info("调用UserDependency.queryBatchUserLevel，请求参数：{}，请求结果：{}",
                JSON.toJSONString(request), JSON.toJSONString(resList));
        return resList;
    }

    /**
     * 批量查询用户信息
     *
     * @param request
     * @return
     */
    public List<UserWideDTO> batchQueryUserInfo(IrisUserWideListQueryRequest request) {
        log.info("调用UserDependency.batchQueryUserInfo，请求参数：{}", JSON.toJSONString(request));

        List<String> uidList = request.getUidList();
        ArrayList<UserWideDTO> resList = Lists.newArrayListWithCapacity(uidList.size());
        List<List<String>> partition = Lists.partition(uidList, maxSize);

        for (List<String> list : partition) {
            request.setUidList(list);
            resList.addAll(doBatchQueryUserInfo(request));
        }

        log.info("调用UserDependency.batchQueryUserInfo，请求参数：{}，请求结果：{}",
                JSON.toJSONString(request), JSON.toJSONString(resList));
        return resList;
    }

    private List<SupervisorUserResponse> doQueryBatchSupervisor(BatchSupervisorRequest request) {
        HttpResult<List<SupervisorUserResponse>> result = supervisorRelationClient.batchQuertSupervisor(request);
        List<SupervisorUserResponse> response = HttpUtils.handleResult(result);
        if (response == null || CollectionUtil.isEmpty(response)) {
            return Collections.emptyList();
        }

        return response;
    }

    private List<UserLevelResponse> doQueryBatchUserLevel(UserLevelBatchRequest request) {
        HttpResult<UserLevelBatchResponse> result = levelClient.queryBatchUserLevel(request);
        UserLevelBatchResponse response = HttpUtils.handleResult(result);
        if (response == null || CollectionUtil.isEmpty(response.getUserLevelResponseList())) {
            return Collections.emptyList();
        }

        return response.getUserLevelResponseList();
    }

    private List<UserWideDTO> doBatchQueryUserInfo(IrisUserWideListQueryRequest request) {
        log.info("调用UserDependency.batchQueryUserInfo，请求参数：{}", JSON.toJSONString(request));
        HttpResult<UserWideListResponse> result = null;
        try {
            result = userWideCoreClient.queryList(request);
        } catch (Exception e) {
            log.error("UserDependency.batchQueryUserInfo请求失败：", e);
        }

        UserWideListResponse response = HttpUtils.handleResult(result);
        if (response == null || CollectionUtil.isEmpty(response.getList())) {
            return Collections.emptyList();
        }

        List<UserWideDTO> list = response.getList();
        log.info("调用UserDependency.batchQueryUserInfo，请求参数：{}，请求结果：{}",
                JSON.toJSONString(request), JSON.toJSONString(list));
        return list;
    }
}
